# Master file
# This script is optional and provided for reference; most users should run analysis scripts directly.
# You must first restart R session before running this script.
# Also before running anything, assert there is no open sink: stopifnot(sink.number() == 0)

start_time <- Sys.time()
stopifnot(sink.number() == 0)
sink("session_info.log", split = FALSE)
cat("Started: ", format(start_time, "%Y-%m-%d %H:%M:%S"), "\n", sep = "")
sink()

# Function ----------------------------------------------------------------

safe_source <- function(file) {
  if (!file.exists(file)) stop("File not found: ", file)

  cat("\n============================================================\n")
  cat("Running:", file, "\n")
  cat("============================================================\n")

  tryCatch(
    source(file, echo = FALSE, print.eval = FALSE),
    error = function(e) {
      cat("\n*** ERROR in:", file, "***\n")
      cat(conditionMessage(e), "\n")
      cat("*** Continuing to next script. ***\n")
    }
  )
}

# Run scripts -------------------------------------------------------------

# Study 1
safe_source("scripts/study1.R")

# Study 2
safe_source("scripts/study2.R")

# Combined analyses across studies
safe_source("scripts/study1_study2_combined.R")

# IRT pre-test
safe_source("scripts/irt_pretest.R")

# Check time and save information -----------------------------------------

end_time <- Sys.time()

# IMPORTANT: ensure no script left a sink open (e.g., due to an error)
while (sink.number() > 0) sink()

# Write session info (master-level)
sink(file.path(getwd(), "session_info.log"), split = FALSE)

hr <- function(title) {
  cat("\n", paste(rep("#", 70), collapse = ""), "\n", sep = "")
  cat("# ", title, "\n", sep = "")
  cat(paste(rep("#", 70), collapse = ""), "\n\n", sep = "")
}

# Runtime
hr("Run Time")
elapsed <- end_time - start_time
cat("Started: ", format(start_time, "%Y-%m-%d %H:%M:%S"), "\n", sep = "")
cat("Ended:   ", format(end_time, "%Y-%m-%d %H:%M:%S"), "\n", sep = "")
cat("Elapsed: ", format(elapsed), "\n", sep = "")

# Session information
hr("Session Information")
print(sessionInfo())

sink()
